import { insertTextAtSelection } from "@ap/util/vscode/insertCode";
import path from "path";
import * as vscode from "vscode";
import { getPackageJson } from "../packageJson";
import { PackageConfig } from "@ap/types/config";
import getFilePath from "../vscode/getFilePath";
import { showWarningMessage } from "../vscode/message";
export async function insertComponent(
  fileUri: vscode.Uri,
  ecsCfg: {
    server: boolean | undefined;
    client: boolean | undefined;
  },
) {
  const file = path.parse(fileUri.fsPath);

  if (file.ext !== ".ts" && file.ext !== ".tsx") {
    showWarningMessage(
      "神岛ECS架构不支持非ts文件，为了促进更好的开发和支持，建议使用 TypeScript 文件。",
    );
    return;
  }

  let presetType = "";
  if (isFileInPath(fileUri, "server", !!ecsCfg.server)) {
    presetType = "GameEntity";
  } else if (isFileInPath(fileUri, "client", !!ecsCfg.client)) {
    presetType = "UiNode";
  } else {
    return;
  }
  const fileName = file.name;
  const document = await vscode.workspace.openTextDocument(fileUri);

  const editor = await vscode.window.showTextDocument(document);
  insertTextAtSelection(
    `import { _decorator, Component, EntityNode } from "@dao3fun/component";
const { apclass } = _decorator;

@apclass("${fileName}")
export class ${fileName} extends Component<${presetType}> {

  start() {

  }

  update(deltaTime: number) {

  }

}`,
    editor,
  );
}

/**
 * 异步获取ESC配置信息
 *
 * 本函数通过读取package.json中的特定配置项来获取ESC的配置信息
 * 主要目的是为了获取服务器端和客户端的ECS配置路径
 *
 * @returns {Promise<ESCConfig>} 返回一个Promise对象，解析为包含服务器端和客户端ECS配置的对象
 *                               如果没有找到相应的配置，则返回null
 */
export async function getESCCfg(): Promise<{
  server: boolean | undefined;
  client: boolean | undefined;
}> {
  // 尝试获取arena专业的地图配置，这是一个异步操作
  const arenaProMapConfig = await getPackageJson<PackageConfig["file"]>("file");

  // 如果找到了配置信息，则构造并返回包含ECS配置的对象
  if (arenaProMapConfig) {
    return {
      server: arenaProMapConfig.typescript.server.ECS,
      client: arenaProMapConfig.typescript.client.ECS,
    };
  }
  return {
    server: undefined,
    client: undefined,
  };
}

function isFileInPath(
  fileUri: vscode.Uri,
  pathType: "server" | "client",
  ecsCfgKey: boolean,
): boolean {
  const filePath = getFilePath(pathType);
  if (!filePath) {
    return false;
  }
  return fileUri.fsPath.startsWith(filePath) && ecsCfgKey;
}
